package com.guoxin.zuche.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;



import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.System;
import android.util.Log;

public class LoadImageAysnc {

	//鍥剧墖缂撳瓨杞紩锟�
	private HashMap<String, SoftReference<Bitmap>> imageCache;
	//绾跨▼锟�
	private BlockingQueue<Runnable> queue;
	private ThreadPoolExecutor executor;
	private String first;
	
	private Map<Integer,String> ids=new LinkedHashMap<Integer,String>();
	public LoadImageAysnc(Context context) {
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
		queue = new LinkedBlockingQueue<Runnable>();
		executor = new ThreadPoolExecutor(3, 15, 180, TimeUnit.SECONDS, queue);
		
	}

	//寮傛鍔犺浇鍥剧墖鐨勬柟娉曪紙鍏跺疄鍙互浠ヤ换浣曞舰寮忓緱鍒板浘鐗囷級
	public Bitmap loadImage(final int position, final String id, final String iconSrc, final String type,final Boolean  Options, final ImageCallBack imageCallBack)
	{
		Log.i("url", iconSrc);
		
		//濡傛灉鏈夌紦瀛樺垯浣跨敤缂撳瓨涓殑鍥剧墖
		if(imageCache.containsKey(id)){
			SoftReference<Bitmap> softReference = imageCache.get(id);
			Bitmap drawable = softReference.get();
			if(drawable != null) {
				if(!Options){
					imageCallBack.imageLoaded(drawable, position);
				 }
				
				return drawable;
			}
		}
		
	 
		
		
		
		//鍥剧墖鍔犺浇瀹屾垚
		final Handler handler = new Handler()
		{
			@Override
			public void handleMessage(Message msg) {
				Bitmap drawable = (Bitmap) msg.obj;
				//鍥剧墖鍔犺浇瀹屾垚鐨勫洖璋冨嚱鏁帮紝鐢ㄤ簬鏇存柊imageview
				imageCallBack.imageLoaded(drawable, position);
			}
		};

		//寮傛鍥剧墖涓嬭浇鏂规硶
		executor.execute(
				new Runnable() {
					@Override
					public void run() {
						Bitmap bitmap = null;
						String filePath = "/sdcard/guoxin/"+id+type;
						File file=new File(filePath);
						if(file.exists()){
							try{
				         
				                bitmap = BitmapFactory.decodeFile(filePath);
				                if(!Options){
								    imageCache.put(id, new SoftReference<Bitmap>(bitmap));
				                }
				                Log.i("test", "------1----");
								Message msg = handler.obtainMessage(0, bitmap);
								msg.sendToTarget();
							}catch (Exception e) {
								e.printStackTrace();
							}
						}else {
							new Thread() {
								@Override
								public void run() {
									InputStream is = null;
//									if(getNetConnectState(context)){
										try {
											HttpURLConnection conn = Util.getHttpURLConnection(iconSrc);
											conn.setDoInput(true);
											if (conn.getResponseCode() == 200) {
												is = conn.getInputStream();
												int size=conn.getContentLength();
												if (is != null) {
							                        BitmapFactory.Options tempBitmapOptions = new BitmapFactory.Options();
							                        tempBitmapOptions.inSampleSize=2;
							                        Bitmap bitmap = BitmapFactory.decodeStream(is, null , tempBitmapOptions);
//													imageCache.put(id, new SoftReference<Bitmap>(bitmap));
							                     
							                        ByteArrayOutputStream baos =new ByteArrayOutputStream();
							                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
							                        
							                        
							                      
													Message msg = handler.obtainMessage(0, bitmap);
													msg.sendToTarget();
													try{
														String filePath = "/sdcard/guoxin/"+id+type;
														if(type.endsWith(".png")){
															saveBitMap_Png(bitmap, filePath);
														}else{
															saveBitMap(bitmap, filePath);
														}
													}catch (Exception e) {
														e.printStackTrace();
													}
													
													baos.close();
													  is.close();
												 }
											    	}
										}catch (Exception e1) {
											e1.printStackTrace();
										}
//									}
									
								 }
								private void saveBitMap(Bitmap bitmap, String filePath)
							    throws IOException, FileNotFoundException {
									File fp = new File("/sdcard/guoxin");
									File file = new File("/sdcard/guoxin/.nomedia");
									if (!fp.exists()) {
										fp.mkdir();
										if((!file.exists())){  
											file.createNewFile();
										}
									}else{
										File f = new File(filePath);
										f.createNewFile();
										FileOutputStream fos = new FileOutputStream(f);
										bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
										fos.flush();
										fos.close();
									}
									}
								
								
								private void saveBitMap_Png(Bitmap bitmap, String filePath)
							    throws IOException, FileNotFoundException {
									File fp = new File("/sdcard/guoxin");
									File file = new File("/sdcard/guoxin/.nomedia");
									if (!fp.exists()) {
										fp.mkdir();
										if((!file.exists())){  
											file.createNewFile();
										}
									}else{
										File f = new File(filePath);
										f.createNewFile();
										FileOutputStream fos = new FileOutputStream(f);
										bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
										fos.flush();
										fos.close();
									}
									}
								
								
								
								}.start();
								 
							// TODO: handle exception
						}
					}
				});
		return null;
	}
	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
			double w = options.outWidth;
			double h = options.outHeight;

			Log.i("width", w+"--"+h);
			
			int lowerBound = (maxNumOfPixels == -1) ? 1 :
			(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
			int upperBound = (minSideLength == -1) ? 128 :
			(int) Math.min(Math.floor(w / minSideLength),
			Math.floor(h / minSideLength));

			if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
			}

			if ((maxNumOfPixels == -1) &&
			(minSideLength == -1)) {
			return 1;
			} else if (minSideLength == -1) {
			return lowerBound;
			} else {
			return upperBound;
			}
			} 
 
	
	//鍥炶皟鎺ュ彛
	public interface ImageCallBack
	{
		public void imageLoaded(Bitmap drawable, int position);
	}
	
	
	  public static InputStream getStreamFromURL(String imageURL) {  
	        InputStream in=null;  
	        try {  
	            URL url=new URL(imageURL);  
	            HttpURLConnection connection=(HttpURLConnection) url.openConnection();  
	            in=connection.getInputStream();  
	              
	        } catch (Exception e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	        return in;  
	          
	    }  
}























